<template>
  <el-dialog
      v-model="dialogVisible"
      title="经费支出新增"
      :close-on-click-modal="false"
      width="80%"
  >
    <div v-loading="loading" class="boxs">
      <div>
        <div class="title-col">项目信息</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称">
            {{projectInfo.name}}
<!--            <el-select v-model="projectInfo.projectId"-->
<!--                       placeholder="请选择项目名称"-->
<!--                       @focus="getprojectOptions"-->
<!--                       @input="handleInput"-->
<!--                       filterable-->
<!--            >-->
<!--              <el-option-->
<!--                  v-for="(item, index) in projectOptions"-->
<!--                  :key="item.id"-->
<!--                  :label="item.name"-->
<!--                  :value="item.id"-->
<!--                  @click="() => changeprojectOptions(item)"-->
<!--              ></el-option>-->
<!--            </el-select>-->
          </el-descriptions-item>
          <el-descriptions-item label="负责人">
            {{ projectInfo.chargerName }}
          </el-descriptions-item>
          <el-descriptions-item label="合同金额（万元）">
            {{ turnWanyuan(projectInfo.feeAuthorize) }}
          </el-descriptions-item>
          <el-descriptions-item label="所属单位">
            {{ projectInfo.unitName }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div>
        <div class="title-col">报销经费</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="报销人">
            {{ userStore.nickName }}
          </el-descriptions-item>
          <el-descriptions-item label="财务项目编号">
            <el-input v-model="projectInfo.feeCode" placeholder="请输入财务项目编号"/>
          </el-descriptions-item>
          <el-descriptions-item label="支出金额（元）">
            {{ projectInfo.payoutFee }}
          </el-descriptions-item>
          <el-descriptions-item label="支出时间">
            {{ projectInfo.payoutDate }}
          </el-descriptions-item>
          <el-descriptions-item label="支出科目">
            <el-input v-model="projectInfo.payoutSubjectName" placeholder="请输入支出科目"/>
          </el-descriptions-item>
          <el-descriptions-item label="摘要">
            <el-input
                v-model="projectInfo.note"
                type="textarea"
                :rows="3"
                placeholder="请输入摘要"
            />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div>
        <div class="flex-title-btn">
          <div class="title-col">报销经费明细</div>
          <el-button @click="addRow" size="small">添加一行</el-button>
        </div>

        <el-table :data="reimbursementDetails" border>
          <el-table-column label="经费来源">
            <template #default="scope">
              <el-select v-model="scope.row.feesource" placeholder="请选择经费来源">
                <el-option value="1" label="专项"></el-option>
                <el-option v-show="projectInfo.projectClass =='zXProject'" value="2" label="配套"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="报销科目名称">
            <template #default="scope">
              <el-tree-select
                  v-model="scope.row.payoutSubjectId"
                  :data="baoxiaokemuOptions"
                  :props="{ label: 'label', value: 'id', children: 'children', }"
                  @node-click="handleSubjectChange(scope.$index,$event)"
                  @focus="getbaoxiaokemuOptions"
              />
            </template>
          </el-table-column>
          <el-table-column label="预算科目名称 (余额/可超金额) 单位：元">
            <template #default="scope">
              <el-tree-select
                  v-model="scope.row.budgetSubjectId"
                  :data="formatBudgetSubjects(budgetSubjects)"
                  :props="{ label: 'value', value: 'code', children: 'children' }"
                  @node-click="handleBudgetSubjectChange(scope.$index, $event)"
                  @focus="getbudgetSubjects(scope.$index , scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="每项报销金额（元）">
            <template #default="scope">
              <el-input-number
                  v-model="scope.row.payoutFee"
                  :min="0"
                  placeholder="请输入每项报销金额"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button plain type="primary" size="small" @click="deleteRow(scope.$index ,scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleSave" type="primary">暂存</el-button>
        <el-button @click="submit" type="primary">提交</el-button>
<!--        <el-button type="primary" @click="handleSaveAndPass">保存并通过</el-button>-->
        <el-button @click="dialogVisible = false" type="primary">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
const loading = ref(false) // 添加加载状态
import { ref, defineEmits, watch } from 'vue';
import { ElMessage, ElNotification } from 'element-plus';
import { getCategory, selectVproject, getpayoutInfo, add } from "@/api/money/jfzcApi.js";
import Cookies from "js-cookie";
import { turnWanyuan } from '@/utils/money.js';
//获取登录中文name
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();

//获取登录name
// 项目名称下拉框选项
const projectOptions = ref([]);
// 处理输入值的函数
const handleInput = (inputValue) => {
  // console.log(inputValue)
  selectVproject({
    pageNum: 1,
    pageSize: 50,
    name: inputValue.data
  })
      .then((res) => {
        projectOptions.value = res.rows
        projectInfo.value.rojectId = res.rows[0].id

      })
};
// 获取项目下拉
const getprojectOptions = () => {
  selectVproject({
    pageNum: 1,
    pageSize: 50,
    projectId:rowID.value
  })
      .then((res) => {
        DialogTop.value = res.rows[0]
        changeprojectOptions()
      })
}
// 点击项目名称下拉
const DialogTop = ref({})
const changeprojectOptions = (itemObj) => {
  //DialogTop.value = projectOptions.value.find((item) => item.id === projectInfo.value.projectId);
  Object.assign(projectInfo.value, DialogTop.value)
  projectInfo.value.id = null
}
// 获取预算科目
const getbudgetSubjects = (index, row) => {
  getpayoutInfo({
    projectId: projectInfo.value.projectId,
    feesource: reimbursementDetails.value[index].feesource,
    projectClass: projectInfo.value.projectClass,
  }).then((res) => {
    budgetSubjects.value = res.data
  })
}
// 处理预算科目名称选择变化
const handleSelectChange = (index, row) => {
  const rowCode = row.budgetSubjectId;
  const selectedSubject = budgetSubjects.value.find(item => item.code === rowCode);
  reimbursementDetails.value[index].budgetSubjectName = selectedSubject.value;
};

// 报销科目名称树形选项
const baoxiaokemuOptions = ref([])
const getbaoxiaokemuOptions = () => {
  getCategory({
    'bizName': '经费支出科目'
  })
      .then((res) => {
        baoxiaokemuOptions.value = res.data
      })
}


// 预算科目名称选项
const budgetSubjects = ref([]);

// 格式化预算科目数据，将 label 和 availableFee 组合
const formatBudgetSubjects = (data) => {
  return data.map(item => {
    const newItem = { ...item };
    if (newItem.availableFee!== undefined) {
      newItem.value = `${newItem.value} (余额: ${newItem.availableFee})`;
    }
    if (newItem.children && newItem.children.length > 0) {
      newItem.children = formatBudgetSubjects(newItem.children);
    }
    return newItem;
  });
};

// 报销经费明细数据
const reimbursementDetails = ref([]);

// 判断是否可以添加行
const canAddRow = () => {
  return reimbursementDetails.value.every(row => {
    return (
        row.feesource &&
        row.payoutSubjectId &&
        row.budgetSubjectId &&
        row.payoutFee > 0
    );
  });
};

// 添加一行数据
const addRow = () => {
  if (canAddRow()) {
    reimbursementDetails.value.push({
      feesource: '1',
      payoutSubjectId: '',
      payoutSubjectName: '',
      budgetSubjectId: '',
      budgetSubjectName: '',
      payoutFee: 0
    });
  } else {
    ElMessage({
      title: '提示',
      message: '请先将表格中的行数据填写完整，再添加新行。',
      type: 'error'
    });
  }
};

// 计算总支出金额
const calculateTotalExpense = () => {
  const total = reimbursementDetails.value.reduce((sum, row) => {
    return sum + Number(row.payoutFee); // 将 row.payoutFee 转换为数值类型
  }, 0);
  projectInfo.value.payoutFee = total;
};
watch(
    () => reimbursementDetails.value.map(row => row.payoutFee),
    () => {
      calculateTotalExpense();
    },
    { deep: true }
);

// 删除一行数据
const deleteRow = (index, row) => {
  reimbursementDetails.value.splice(index, 1);
};

// 处理报销科目名称选择变化
const handleSubjectChange = (index, data) => {
  reimbursementDetails.value[index].payoutSubjectName = data.label;
};
function findSubjectInTree(tree, rowCode) {
  for (let i = 0; i < tree.length; i++) {
    const item = tree[i];
    if (item.code === rowCode) {
      return item;
    }
    if (item.children && item.children.length > 0) {
      const found = findSubjectInTree(item.children, rowCode);
      if (found) {
        return found;
      }
    }
  }
  return undefined;
}
// 处理预算科目名称树形选择变化
const handleBudgetSubjectChange = (index, data, node) => {
  console.log(data.children)
  if (!data.children || data.children.length == 0) {
    const rowCode = data.code;
    console.log( data.code)
    //const selectedSubject = budgetSubjects.value.find(item => item.code === rowCode);
    const selectedSubject = findSubjectInTree(budgetSubjects.value, rowCode);
    console.log(budgetSubjects.value,'budgetSubjects')
    console.log(selectedSubject,'selectedSubject')
    reimbursementDetails.value[index].budgetSubjectName = selectedSubject.value;
    reimbursementDetails.value[index].budgetSubjectId = rowCode;
    reimbursementDetails.value[index].budgetSubjectBalance = selectedSubject.availableFee;
    console.log(reimbursementDetails.value[index],'reimbursementDetails.value[index]')
  } else {
    reimbursementDetails.value[index].budgetSubjectName = null;
    reimbursementDetails.value[index].budgetSubjectId = null;
    reimbursementDetails.value[index].budgetSubjectBalance = null;
  }
  // console.log(index, data, node)
  // if (!data.children) {
  //   const rowCode = data.code;
  //   const selectedSubject = budgetSubjects.value.find(item => item.code === rowCode);
  //   reimbursementDetails.value[index].budgetSubjectName = selectedSubject.value;
  //   reimbursementDetails.value[index].budgetSubjectId = rowCode;
  // } else {
  //   reimbursementDetails.value[index].budgetSubjectName = null;
  //   reimbursementDetails.value[index].budgetSubjectId = null;
  // }
};

// 控制弹窗显示与隐藏的变量
const dialogVisible = ref(false);
// 获取当前日期
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const day = String(currentDate.getDate()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;
// 模拟项目信息数据
const projectInfo = ref({
  status: '-1',
  checkstatus: '',
  projectId: "",
  projectName: "",
  chargerName: "",
  feeAuthorize: '',
  unitId: '',
  unitName: '',
  projectClass: '',
  payoutPersonName: userStore.nickName,
  payoutPersonId:userStore.userRealId,
  feeCode: "",
  payoutFee: 0,
  payoutDate: formattedDate,
  payoutSubjectName: "",
  note: "",
  payoutDetails: []
});

// 报销经费信息
const reimbursementInfo = ref({
  reimburser: '李四',
  financialProjectNumber: '',
  expenseAmount: 0,
  expenseDate: formattedDate,
  expenseSubject: '',
  summary: ''
});

// 提交按钮点击事件处理函数
const submit = () => {

  projectInfo.value.status = '1';
  projectInfo.value.payoutDetails = reimbursementDetails.value;
  if (projectInfo.value.payoutFee == 0) {
    ElMessage({
      message: '支出金额为0',
      type: 'error'
    });
    return;
  }
  if (!canAddRow()) {
    ElMessage({
      title: '提示',
      message: '请先将表格中的行数据填写完整，再添加新行。',
      type: 'warning'
    });
    return;
  }
  if (!checkPayoutFeeValid()) {
    ElNotification({
      title: '提示',
      message: '每项报销金额必须小于等于预算科目余额',
      type: 'warning'
    });
    return;
  }
  loading.value = true
  add(projectInfo.value)
      .then((res) => {
        if (res.code === 200) {
          ElMessage({
            message: res.msg,
            type: 'success',
          });
          dialogVisible.value = false;
          emits('getslist');
        } else {
          ElMessage({
            message: res.msg,
            type: 'error',
          });
        }
      })
      .finally(() => {
        loading.value = false // 结束加载
      })
};

// 保存按钮点击事件处理函数
const handleSave = () => {

  projectInfo.value.status = '-1';
  projectInfo.value.payoutDetails = reimbursementDetails.value;
  // console.log(userStore.nickName)
  // console.log(projectInfo.value)
  // return;
  if (projectInfo.value.payoutFee == 0) {
    ElMessage({
      message: '支出金额为0',
      type: 'error'
    });
    return;
  }
  if (!canAddRow()) {
    ElMessage({
      title: '提示',
      message: '请先将表格中的行数据填写完整，再添加新行。',
      type: 'warning'
    });
    return;
  }
  if (!checkPayoutFeeValid()) {
    ElNotification({
      title: '提示',
      message: '每项报销金额必须小于等于预算科目余额',
      type: 'warning'
    });
    return;
  }
  loading.value = true // 开始加载
  add(projectInfo.value)
      .then((res) => {
        if (res.code === 200) {
          ElMessage({
            message: res.msg,
            type: 'success',
          });
          dialogVisible.value = false;
          emits('getslist');
        } else {
          ElMessage({
            message: res.msg,
            type: 'error',
          });
        }
      })
      .finally(() => {
        loading.value = false // 结束加载
      })
};

// 保存并通过按钮点击事件处理函数
const handleSaveAndPass = () => {
  projectInfo.value.status = '2';
  projectInfo.value.payoutDetails = reimbursementDetails.value;
  if (projectInfo.value.payoutFee == 0) {
    ElMessage({
      message: '支出金额为0',
      type: 'error'
    });
    return;
  }
  if (!canAddRow()) {
    ElMessage({
      // title: '提示',
      message: '请先将表格中的行数据填写完整，再添加新行。',
      type: 'warning'
    });
    return;
  }
  if (!checkPayoutFeeValid()) {
    ElNotification({
      title: '提示',
      message: '每项报销金额必须小于等于预算科目余额',
      type: 'warning'
    });
    return;
  }
  add(projectInfo.value)
      .then((res) => {
        if (res.code === 200) {
          ElMessage({
            message: res.msg,
            type: 'success',
          });
          dialogVisible.value = false;
          emits('getslist');
        } else {
          ElMessage({
            message: res.msg,
            type: 'error',
          });
        }
      });
};
// 检查每项报销金额是否小于等于预算科目余额
const checkPayoutFeeValid = () => {
  return reimbursementDetails.value.every(row => {
    console.log(row.budgetSubjectBalance)
    if(row.budgetSubjectBalance){
      console.log(row.payoutFee,row.budgetSubjectBalance,row)
      return row.payoutFee <= row.budgetSubjectBalance;
    }else {
      console.log(row.payoutFee,row.availableFee,row)
      return row.payoutFee <= row.availableFee;
    }

  });
};
// 定义事件，用于通知父组件保存操作
const emits = defineEmits(['getslist',]);
// 定义一个方法用于打开弹窗
const rowID = ref('')
const openDialog = (row) => {
 // alert(row)
  if(!row){
   // alert(' meiyou id')
  }
  rowID.value = row
  projectInfo.value.projectId = row
  // 清空报销经费明细
  reimbursementDetails.value = [];
  projectInfo.value.payoutSubjectName = ''
  projectInfo.value.feeCode = ''
  projectInfo.value.note = ''
  dialogVisible.value = true;
  getprojectOptions()


  //projectInfo.value.projectId = '';
};

// 暴露 openDialog 方法供父组件调用
defineExpose({
  openDialog
});
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}

/* 设置标题宽度 */
:deep(.el-descriptions__label) {
  width: 200px;
}

/* 让内容居中显示 */
:deep(.el-descriptions__content) {
  text-align: center;
}

.title-col {
  color: #337AB7;
  font-weight: bolder;
  margin: 10px 0;
}

.flex-title-btn {
  display: flex;
  justify-content: space-between;
}

.boxs > div {
  margin: 10px 0;
}
</style>